<template>
  <div class="weather-query-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>
        <el-icon><Sunny /></el-icon>
        全国天气查询系统
      </h2>
      <p class="page-desc">点击地图上的任意位置，即可查询该地区的实时天气信息</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：地图区域 -->
      <el-col :span="16">
        <el-card class="map-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>全国地图</span>
              <el-button 
                type="text" 
                size="small" 
                @click="resetMap"
                :icon="Refresh"
              >
                重置视图
              </el-button>
            </div>
          </template>
          <div id="map-container" class="map-container" v-loading="mapLoading"></div>
        </el-card>
      </el-col>

      <!-- 右侧：天气信息 -->
      <el-col :span="8">
        <el-card class="weather-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>天气信息</span>
            </div>
          </template>
          
          <div class="weather-info" v-if="selectedLocation.city">
            <!-- 位置信息 -->
            <div class="location-section">
              <div class="location-title">
                <el-icon><Location /></el-icon>
                <span>{{ selectedLocation.city }}</span>
              </div>
              <div class="location-detail" v-if="selectedLocation.province">
                {{ selectedLocation.province }}
                <span v-if="selectedLocation.district"> · {{ selectedLocation.district }}</span>
              </div>
              <div class="location-coords">
                坐标：{{ selectedLocation.lat.toFixed(4) }}, {{ selectedLocation.lon.toFixed(4) }}
              </div>
            </div>

            <!-- 天气详情 -->
            <div class="weather-detail" v-if="weatherData.temp">
              <div class="weather-main">
                <div class="weather-icon-large">
                  <el-icon v-if="weatherData.icon === 'sunny'"><Sunny /></el-icon>
                  <el-icon v-else-if="weatherData.icon === 'cloudy'"><Cloudy /></el-icon>
                  <el-icon v-else><PartlyCloudy /></el-icon>
                </div>
                <div class="weather-temp-main">
                  <span class="temp-value">{{ weatherData.temp }}</span>
                  <span class="temp-unit">°C</span>
                </div>
                <div class="weather-desc-main">{{ weatherData.desc }}</div>
              </div>

              <el-divider />

              <!-- 详细天气数据 -->
              <div class="weather-stats">
                <div class="stat-item">
                  <div class="stat-label">
                    <el-icon><WindPower /></el-icon>
                    风速
                  </div>
                  <div class="stat-value">{{ weatherData.windSpeed || '--' }} m/s</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">
                    <el-icon><Drizzling /></el-icon>
                    湿度
                  </div>
                  <div class="stat-value">{{ weatherData.humidity || '--' }}%</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">
                    <el-icon><Compass /></el-icon>
                    气压
                  </div>
                  <div class="stat-value">{{ weatherData.pressure || '--' }} hPa</div>
                </div>
              </div>

              <!-- 更新时间 -->
              <div class="update-time">
                <el-icon><Clock /></el-icon>
                更新时间：{{ updateTime }}
              </div>
            </div>

            <!-- 空状态 -->
            <div class="empty-weather" v-else>
              <el-empty description="请在地图上点击选择位置查询天气" :image-size="100" />
            </div>
          </div>

          <!-- 未选择位置 -->
          <div class="empty-weather" v-else>
            <el-empty description="请在地图上点击选择位置查询天气" :image-size="100" />
          </div>
        </el-card>

        <!-- 最近查询记录 -->
        <el-card class="history-card" shadow="never" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>最近查询</span>
            </div>
          </template>
          <div class="history-list">
            <div 
              v-for="(item, index) in queryHistory" 
              :key="index"
              class="history-item"
              @click="selectHistoryItem(item)"
            >
              <div class="history-city">{{ item.city }}</div>
              <div class="history-time">{{ item.time }}</div>
            </div>
            <div v-if="queryHistory.length === 0" class="history-empty">
              暂无查询记录
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Sunny, Location, Refresh, Clock, WindPower, Drizzling, Compass,
  Cloudy, PartlyCloudy
} from '@element-plus/icons-vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

// 注意：Leaflet 图标路径问题，如果图标不显示，可以注释掉以下代码
// 我们使用自定义的 divIcon，所以不需要默认图标

const mapLoading = ref(false)
const map = ref(null)
const marker = ref(null)
const selectedLocation = ref({
  city: '',
  province: '',
  district: '',
  lat: 0,
  lon: 0
})
const weatherData = ref({
  temp: '',
  desc: '',
  icon: 'sunny',
  windSpeed: '',
  humidity: '',
  pressure: ''
})
const updateTime = ref('')
const queryHistory = ref([])

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (map.value) {
    map.value.remove()
  }
})

// 初始化地图
const initMap = () => {
  mapLoading.value = true
  
  // 延迟初始化，确保DOM已渲染
  setTimeout(() => {
    try {
      // 创建地图实例，中心点设置为中国中心（约北京）
      map.value = L.map('map-container', {
        center: [35.8617, 104.1954], // 中国中心坐标
        zoom: 5,
        minZoom: 3,
        maxZoom: 18
      })

      // 添加地图图层（使用OpenStreetMap免费地图）
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
      }).addTo(map.value)

      // 添加点击事件
      map.value.on('click', handleMapClick)

      // 添加默认标记（北京）
      addMarker(39.9042, 116.4074, '北京')
      
      mapLoading.value = false
    } catch (error) {
      console.error('地图初始化失败:', error)
      ElMessage.error('地图加载失败，请刷新页面重试')
      mapLoading.value = false
    }
  }, 100)
}

// 处理地图点击事件
const handleMapClick = async (e) => {
  const { lat, lng } = e.latlng
  
  // 添加标记
  addMarker(lat, lng)
  
  // 获取城市信息
  await getCityByCoordinates(lat, lng)
  
  // 查询天气
  await getWeather(lat, lng)
  
  // 添加到查询历史
  addToHistory()
}

// 添加地图标记
const addMarker = (lat, lng, cityName = '') => {
  // 移除旧标记
  if (marker.value) {
    map.value.removeLayer(marker.value)
  }
  
  // 创建自定义图标
  const icon = L.divIcon({
    className: 'custom-marker',
    html: `<div style="
      width: 30px;
      height: 30px;
      background: #409eff;
      border: 3px solid #fff;
      border-radius: 50%;
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    "></div>`,
    iconSize: [30, 30],
    iconAnchor: [15, 15]
  })
  
  // 添加新标记
  marker.value = L.marker([lat, lng], { icon }).addTo(map.value)
  
  // 如果有城市名，添加弹窗
  if (cityName) {
    marker.value.bindPopup(cityName).openPopup()
  }
  
  // 移动地图视图到标记位置
  map.value.setView([lat, lng], map.value.getZoom())
}

// 通过坐标获取城市信息（模拟数据）
const getCityByCoordinates = async (lat, lon) => {
  // 使用模拟数据，根据坐标范围判断大概位置
  const cities = [
    { name: '北京', province: '北京市', lat: 39.9042, lon: 116.4074 },
    { name: '上海', province: '上海市', lat: 31.2304, lon: 121.4737 },
    { name: '广州', province: '广东省', lat: 23.1291, lon: 113.2644 },
    { name: '深圳', province: '广东省', lat: 22.5431, lon: 114.0579 },
    { name: '杭州', province: '浙江省', lat: 30.2741, lon: 120.1551 },
    { name: '成都', province: '四川省', lat: 30.6624, lon: 104.0633 },
    { name: '西安', province: '陕西省', lat: 34.3416, lon: 108.9398 },
    { name: '武汉', province: '湖北省', lat: 30.5928, lon: 114.3055 },
    { name: '南京', province: '江苏省', lat: 32.0603, lon: 118.7969 },
    { name: '重庆', province: '重庆市', lat: 29.5630, lon: 106.5516 }
  ]
  
  // 找到距离最近的城市
  let nearestCity = cities[0]
  let minDistance = Infinity
  
  cities.forEach(city => {
    const distance = Math.sqrt(
      Math.pow(city.lat - lat, 2) + Math.pow(city.lon - lon, 2)
    )
    if (distance < minDistance) {
      minDistance = distance
      nearestCity = city
    }
  })
  
  // 如果距离太远，使用通用名称
  if (minDistance > 5) {
    selectedLocation.value = {
      city: `位置 ${lat.toFixed(2)}, ${lon.toFixed(2)}`,
      province: '未知省份',
      district: '',
      lat: lat,
      lon: lon
    }
  } else {
    selectedLocation.value = {
      city: nearestCity.name,
      province: nearestCity.province,
      district: '',
      lat: lat,
      lon: lon
    }
  }
}

// 获取天气信息
const getWeather = async (lat, lon) => {
  try {
    // 注意：这里使用模拟数据，实际使用时需要配置天气API
    // 可以注册 OpenWeatherMap 或其他天气API服务
    
    // 模拟天气数据
    const mockWeather = {
      temp: Math.round(15 + Math.random() * 20), // 15-35度
      desc: ['晴朗', '多云', '阴天', '小雨'][Math.floor(Math.random() * 4)],
      icon: ['sunny', 'cloudy', 'cloudy', 'cloudy'][Math.floor(Math.random() * 4)],
      windSpeed: (2 + Math.random() * 8).toFixed(1),
      humidity: Math.round(40 + Math.random() * 40),
      pressure: Math.round(1000 + Math.random() * 50)
    }
    
    weatherData.value = mockWeather
    
    // 更新更新时间
    const now = new Date()
    updateTime.value = now.toLocaleString('zh-CN')
    
    // 如果有真实的API Key，可以取消注释以下代码
    /*
    const apiKey = 'YOUR_API_KEY' // 替换为实际的API Key
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`
    const response = await fetch(url)
    const data = await response.json()
    
    if (data.main) {
      weatherData.value = {
        temp: Math.round(data.main.temp),
        desc: data.weather[0]?.description || '未知',
        icon: getWeatherIcon(data.weather[0]?.main),
        windSpeed: data.wind?.speed?.toFixed(1) || '--',
        humidity: data.main.humidity || '--',
        pressure: data.main.pressure || '--'
      }
      updateTime.value = new Date().toLocaleString('zh-CN')
    }
    */
  } catch (error) {
    console.error('获取天气失败:', error)
    ElMessage.error('获取天气信息失败')
  }
}

// 添加到查询历史
const addToHistory = () => {
  if (!selectedLocation.value.city) return
  
  const historyItem = {
    city: selectedLocation.value.city,
    province: selectedLocation.value.province,
    lat: selectedLocation.value.lat,
    lon: selectedLocation.value.lon,
    time: new Date().toLocaleString('zh-CN')
  }
  
  // 检查是否已存在
  const exists = queryHistory.value.find(
    item => item.city === historyItem.city && 
            Math.abs(item.lat - historyItem.lat) < 0.01
  )
  
  if (!exists) {
    queryHistory.value.unshift(historyItem)
    // 只保留最近10条
    if (queryHistory.value.length > 10) {
      queryHistory.value = queryHistory.value.slice(0, 10)
    }
  }
}

// 选择历史记录
const selectHistoryItem = async (item) => {
  addMarker(item.lat, item.lon, item.city)
  selectedLocation.value = {
    city: item.city,
    province: item.province || '',
    district: '',
    lat: item.lat,
    lon: item.lon
  }
  await getWeather(item.lat, item.lon)
}

// 重置地图视图
const resetMap = () => {
  if (map.value) {
    map.value.setView([35.8617, 104.1954], 5)
    ElMessage.info('地图视图已重置')
  }
}
</script>

<style lang="scss" scoped>
.weather-query-container {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 8px 0;
      
      .el-icon {
        font-size: 28px;
        color: #f39c12;
      }
    }
    
    .page-desc {
      color: #909399;
      font-size: 14px;
      margin: 0;
    }
  }
  
  .map-card, .weather-card, .history-card {
    border-radius: 8px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .map-container {
    width: 100%;
    height: 600px;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .weather-info {
    .location-section {
      margin-bottom: 24px;
      padding-bottom: 20px;
      border-bottom: 1px solid #e4e7ed;
      
      .location-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 8px;
        
        .el-icon {
          color: #409eff;
          font-size: 22px;
        }
      }
      
      .location-detail {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
      
      .location-coords {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .weather-detail {
      .weather-main {
        text-align: center;
        padding: 20px 0;
        
        .weather-icon-large {
          font-size: 64px;
          color: #f39c12;
          margin-bottom: 16px;
        }
        
        .weather-temp-main {
          display: flex;
          align-items: flex-start;
          justify-content: center;
          gap: 4px;
          margin-bottom: 8px;
          
          .temp-value {
            font-size: 48px;
            font-weight: 600;
            color: #303133;
            line-height: 1;
          }
          
          .temp-unit {
            font-size: 24px;
            color: #909399;
            margin-top: 8px;
          }
        }
        
        .weather-desc-main {
          font-size: 16px;
          color: #606266;
        }
      }
      
      .weather-stats {
        display: flex;
        flex-direction: column;
        gap: 16px;
        
        .stat-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px;
          background: #f5f7fa;
          border-radius: 6px;
          
          .stat-label {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #606266;
            font-size: 14px;
            
            .el-icon {
              color: #409eff;
            }
          }
          
          .stat-value {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
        }
      }
      
      .update-time {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: #909399;
        margin-top: 20px;
        padding-top: 16px;
        border-top: 1px solid #e4e7ed;
        
        .el-icon {
          font-size: 14px;
        }
      }
    }
    
    .empty-weather {
      min-height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .history-list {
    max-height: 300px;
    overflow-y: auto;
    
    .history-item {
      padding: 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;
      margin-bottom: 8px;
      
      &:hover {
        background: #f5f7fa;
      }
      
      .history-city {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .history-time {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .history-empty {
      text-align: center;
      color: #909399;
      font-size: 14px;
      padding: 40px 0;
    }
  }
}

// Leaflet 自定义标记样式
:deep(.custom-marker) {
  background: transparent;
  border: none;
}
</style>
